﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LiaoChengFei.Core
{
  public static class ServiceColletionExtensions
    {
        public static void AdddAssembly(this IServiceCollection services,string assemblyName, ServiceLifetime serviceLifetime= ServiceLifetime.Scoped) 
        {
            var assembly = RunTimeHelper.GetAssemblyByName(assemblyName);
            var types = assembly.GetTypes();
            var list = types.Where(u => u.IsClass && !u.IsAbstract && !u.IsGenericType).ToList();
            foreach (var type in list)
            {
                var interfaceList = type.GetInterfaces();
                if (interfaceList.Any())
                {
                    var inter = interfaceList.First();
                    switch (serviceLifetime)
                    {
                        case ServiceLifetime.Scoped:
                            services.AddScoped(inter,type);
                            break;
                        case ServiceLifetime.Singleton:
                            services.AddSingleton(inter, type);
                            break;
                        case ServiceLifetime.Transient:
                            services.AddTransient(inter, type);
                            break;
                    }
                }
            }
        }
    }
}
